import sys
import os

from aws_model.athena_submit import submit

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import *
import boto3
from base_class.base_utils import spend_time
from base_class.inspect_logging import print_to_log
from delete import delete_data


# 源表和目标表
# client = boto3.client('athena')


@spend_time("一个型号一天耗时： ")
def insert_ac_mapping(is_hour, mappings, p_date, materials):
    if p_date < '2022-01-01':
        source_table = ac_history_table
        target_table = ac_target_table
    elif is_hour:
        source_table = ac_hbase_table_hour
        target_table = ac_target_table_hour
    else:
        source_table = ac_hbase_table
        target_table = ac_target_table
    for m in materials:
        delete_data(target_table, p_date, m)
    source_columns = [f'"COALESCE(TRY(CAST ({mapping["original_field"]} AS {mapping["data_type"]})),null)"'
                      for mapping in mappings]
    target_columns = [f'"{mapping["natrual_field"]}"' for mapping
                      in mappings]
    # 重复的字段的数据来源"

    if p_date >= AC_LINE_TIME:
        query = f"""INSERT INTO {target_table} (sn, timeStamp, {",".join(target_columns)})
        SELECT
                    substr(rowkey, 27, 24) as sn ,
                    date_format(from_unixtime(cast(substr(cast(9223372036854775807-cast(substr(rowkey, 8, 19) as bigint) as varchar),1,10) as bigint), 'Asia/Shanghai'), '%Y-%m-%d %H:%i:%s' ) as timeStamp,
                    {",".join(source_columns)} FROM {source_table} WHERE """
    else:
        query = f"""INSERT INTO {target_table} ({",".join(target_columns)})
            SELECT {",".join(source_columns)} FROM {source_table}
             WHERE """
    query = query.replace('"', "")
    query += f" p_date = '{p_date}' "
    query += f''' and material in ({"'" + "','".join(materials) + "'"}) '''
    result = submit(query)
    print_to_log(materials + ": ", p_date, result)
